package com.cqie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cqie.dto.PrescriptionInfo.PrescriptionInfoDto;
import com.cqie.dto.TokenUserLoginDto;
import com.cqie.dto.caseDto.AddCaseInfoDto;
import com.cqie.entity.CaseInfo;
import com.cqie.exception.SpecialException;
import com.cqie.mapper.CaseInfoMapper;
import com.cqie.service.ICaseInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cqie.service.IPrescriptionInfoService;
import com.cqie.threadlocal.UserThreadLocal;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;

/**
 * <p>
 * 病案信息 服务实现类
 * </p>
 *
 * @author 不吃海鲜
 * @since 2024-12-25
 */
@Service
@Slf4j
public class CaseInfoServiceImpl extends ServiceImpl<CaseInfoMapper, CaseInfo> implements ICaseInfoService {
    @Resource
    private CaseInfoMapper caseInfoMapper;



    /**
     * 新增病例
     *
     * @param addCaseInfoDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addCaseInfo(AddCaseInfoDto addCaseInfoDto) throws SpecialException {

        log.info(addCaseInfoDto.toString());

        if (ObjectUtils.isEmpty(addCaseInfoDto.getPatientId())) {
            throw new SpecialException("患者id不能为空");
        }

        if (ObjectUtils.isEmpty(addCaseInfoDto.getDoctorId())) {
            throw new SpecialException("主治医生id不能为空");
        }

        if (ObjectUtils.isEmpty(addCaseInfoDto.getCaseResult())) {
            throw new SpecialException("诊断结果不能为空");
        }

        addCaseInfoDto.setCaseCode(generateCaseCode());
        LocalDateTime now = LocalDateTime.now();
        addCaseInfoDto.setCreateTime(now);


        return caseInfoMapper.addCaseInfo(addCaseInfoDto);
    }

    /**
     * 查询病例
     *
     * @param likeQuery      患者姓名/病历号
     * @param departmentName 科室名称
     * @param pageSize       每页大小
     * @param pageIndex      页码
     * @return
     */
    @Override
    public List<CaseInfo> getCaseInfo(String likeQuery, String departmentName, Integer pageSize, Integer pageIndex) {

        // 获取当前医生登陆信息
        TokenUserLoginDto tokenDto = UserThreadLocal.get(TokenUserLoginDto.class);

        Page<CaseInfo> page = new Page<>(pageIndex, pageSize);

        LambdaQueryWrapper<CaseInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CaseInfo::getDoctorId, tokenDto.getDoctorId())
                .eq(CaseInfo::getRmSign, "0")
                .like(ObjectUtils.isNotEmpty(departmentName), CaseInfo::getDoctorDepartmentName, departmentName);

        // 如果likeQuery不为空，则同时对PatientName和CaseCode添加like查询
        if (ObjectUtils.isNotEmpty(likeQuery)) {
            queryWrapper.and(s -> s
                    .like(CaseInfo::getPatientName, likeQuery)
                    .or()
                    .like(CaseInfo::getCaseCode, likeQuery)
            );
        }

        IPage<CaseInfo> result = caseInfoMapper.selectPage(page, queryWrapper);
        return result.getRecords();
    }

    /**
     * 作废病例
     * @param caseCode
     * @return
     */
    @Override
    public Boolean deleteCaseInfo(String caseCode) {
        if (ObjectUtils.isEmpty(caseCode)) {
            return false;
        }

        return caseInfoMapper.deleteCaseInfo(caseCode);
    }


    /**
     * 根据病案编号修改当前开药状态
     * @param caseCode
     * @return
     */
    @Override
    public Boolean updateIsPrescribe(String caseCode) {
        return caseInfoMapper.updateIsPrescribe(caseCode);
    }


    /**
     * 根据病案编号修改当前未开药状态
     * @param caseCode
     * @return
     */
    @Override
    public Boolean removeIsPrescribe(String caseCode) {
        return caseInfoMapper.removeIsPrescribe(caseCode);
    }


    /**
     * 生成病例编号
     *
     * @return
     */
    private String generateCaseCode() {
        String caseCode = "BA";


        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 8; i++) {
            // 随机生成0到9之间的整数，并追加到StringBuilder对象中
            sb.append(random.nextInt(10));
        }

        caseCode += sb.toString();

        // 数据库查询是否存在相同的
        var num = caseInfoMapper.getCaseCode(caseCode);
        if (num > 0) {
            return generateCaseCode();
        }

        return caseCode;
    }
}
